<?php

namespace app\madmin\service;

use app\madmin\model\OrderCommodity;
use app\utils\TrimData;
use think\db\Query;
use think\Validate;
use think\model\Relation;
use think\Exception;
use think\facade\Db;
use app\madmin\model\Group;
use app\madmin\model\Collage;
use app\madmin\validate\GroupValidate;
use app\madmin\model\GroupCommodity;
use WePayV3\Order;

class GroupService
{

    private function buildWhere(array $data)
    {
        $where = [];
        !empty($data['status']) && $where[] = ['status', 'in', $data['status']];
        return $where;
    }

    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function index($page = 1, $size = 10, $search = [])
    {
        $list = Group::where($this->buildWhere($search))->order('status ASC')->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 保存数据
     * @param array $data
     * @return array
     * @throws
     */
    public function save(array $data)
    {
        $check = Group::check($data);
        try {
            Db::startTrans();
            $group = Group::create($check['group']);
            foreach ($check['commodity'] as $key => $value) {
                $commodity = $group->commodity()->save($value);
                if ($value['has_sku'] == 1) {
                    $commodity->sku()->saveAll($value['skus']);
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage(), HTTP_NOTACCEPT);
        }
        return [HTTP_CREATED, $group];
    }

    /**
     * 读取一条数据
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(int $id)
    {
        $model = Group::with(['commodity' => function ($sql) {
            $sql->with(['goods', 'sku' => function ($query) {
                $query->with('sku');
            }]);
        }])->find($id);
        return [HTTP_SUCCESS, $model];
    }


    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return array
     * @throws
     */
    public function update(int $id, array $data)
    {
        try {
            Db::startTrans();
            $rules = json_decode(Group::find($id)['rules'], true);
            $rules['is_show'] = $data['is_show'];
            $update = [
                'rules' => json_encode($rules),
                'end_time' => $data['end_time']
            ];
            $goods_update = [
                'show_time' => null,
                'end_time' => $data['end_time']
            ];
            if ($data['is_show'][0] == 1) {
                $goods_update['show_time'] = $data['is_show'][1];
            }
            // 过期
            if ($data['end_time'] < date("Y-m-d H:i:s", time())) {
                $update['status'] = 2;
                $goods_update['status'] = 2;
            }
            Group::update($update, ['id' => $id]);
            GroupCommodity::update($goods_update, ['group_id' => $id]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception("发生错误！", HTTP_NOTACCEPT);
        }
        return [HTTP_CREATED, "更新成功！"];
    }

    /**
     * @param $id
     * @return array
     */
    public function stop($id)
    {
        try {
            Group::update([
                'close_time' => date('Y-m-d H:i:s', time()),
                'status' => 2
            ], ['id' => $id]);
            $res = GroupCommodity::update(['status' => 2], ['group_id' => $id]);
            $ids = array_column(GroupCommodity::field('id')->where('group_id', $id)->select()->toArray(), 'id');
            foreach ($ids as $ia => $iv) {
                GroupCommodity::finishCollage($iv);
            }
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception("发生错误！", HTTP_NOTACCEPT);
        }
        return [HTTP_CREATED, $res];
    }

    /**
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        Group::update(['status' => 2], ['id' => $id]);
        GroupCommodity::update(['status' => 2], ['group_id' => $id]);
        $ids = array_column(GroupCommodity::field('id')->where('group_id', $id)->select()->toArray(), 'id');
        foreach ($ids as $ia => $iv) {
            GroupCommodity::finishCollage($iv);
        }
        Group::destroy($id);
        return HTTP_NOCONTEND;
    }

    public function data()
    {
        $amount = OrderCommodity::where('gc_id' , "<>", 0)->where(function ($sql) {
                        $sql->where('status', 2)->whereOr(function ($sql) {
                            $sql->where(['status' => 11, 'after_type' => 1]);
                        });
                    })->sum("money");
        $order = OrderCommodity::where('gc_id' , "<>", 0)->count("id");
        $commodity = GroupCommodity::group('commodity_id')->count("id");
        $res = [
            'amount' => $amount,
            'order' => $order,
            'commodity' => $commodity
        ];
        return [HTTP_CREATED, $res];
    }

    public function dataForGroup($page = 1, $size = 10)
    {
        $list = Group::field('id,type,title,start_time,end_time,close_time')->order('id DESC')->paginate(['page' => $page, 'list_rows' => $size]);
        foreach ($list as $key => $value) {
            $gc = GroupCommodity::field('id')->where('group_id', $value['id'])->select();
            $gc_id = empty($gc) ? [] : array_column($gc->toArray(), 'id');
            if ($value['type'] == 2) {
                $gc_arr = [];
                foreach ($gc_id as $gk => $gv) {
                    for ($i = 0; $i < 3; $i++) {
                        array_push($gc_arr, $gv. ',' . $i);
                    }
                }
                $gc_id = $gc_arr;
            }

            $list[$key]['order'] = OrderCommodity::where('gc_id', 'in', $gc_id)->count('id');
            $list[$key]['amount'] = OrderCommodity::where('gc_id', 'in', $gc_id)->sum('money');
            $list[$key]['refund'] = OrderCommodity::where('gc_id', 'in', $gc_id)
                ->where('status', 11)
                ->where('after_type', 1)
                ->sum('money');
            $list[$key]['people'] = Db::name('order_commodity')->alias('a')
                ->join('order o', 'a.order_id = o.id')
                ->where('a.gc_id', 'in', $gc_id)
                ->group('o.user_id')
                ->count("a.id");
        }
        return [HTTP_SUCCESS, $list];
    }

}
